{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "2709600a",
   "metadata": {},
   "outputs": [
    {
     "ename": "ModuleNotFoundError",
     "evalue": "No module named 'talib'",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mModuleNotFoundError\u001b[0m                       Traceback (most recent call last)",
      "\u001b[1;32m~\\AppData\\Local\\Temp\\ipykernel_19548\\3016012301.py\u001b[0m in \u001b[0;36m<module>\u001b[1;34m\u001b[0m\n\u001b[0;32m      2\u001b[0m \u001b[1;31m#当MACD信号小于0卖出。\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m      3\u001b[0m \u001b[1;31m#当MACD信号大于0买入。\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 4\u001b[1;33m \u001b[1;32mimport\u001b[0m \u001b[0mtalib\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m      5\u001b[0m \u001b[1;32mimport\u001b[0m \u001b[0mnumpy\u001b[0m \u001b[1;32mas\u001b[0m \u001b[0mnp\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m      6\u001b[0m \u001b[1;32mimport\u001b[0m \u001b[0mpandas\u001b[0m \u001b[1;32mas\u001b[0m \u001b[0mpd\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;31mModuleNotFoundError\u001b[0m: No module named 'talib'"
     ]
    }
   ],
   "source": [
    "\n",
    "#此例子采用Talib提供的MACD指标作为买入/卖出信号。\n",
    "#当MACD信号小于0卖出。\n",
    "#当MACD信号大于0买入。\n",
    "import talib\n",
    "import numpy as np\n",
    "import pandas as pd"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "b055d08d",
   "metadata": {},
   "outputs": [
    {
     "ename": "NameError",
     "evalue": "name 'set_universe' is not defined",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mNameError\u001b[0m                                 Traceback (most recent call last)",
      "\u001b[1;32m~\\AppData\\Local\\Temp\\ipykernel_19548\\3778895150.py\u001b[0m in \u001b[0;36m<module>\u001b[1;34m\u001b[0m\n\u001b[0;32m      2\u001b[0m \u001b[0mstocks\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;33m[\u001b[0m\u001b[1;34m'000001.XSHE'\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;34m'000002.XSHE'\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;34m'000004.XSHE'\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;34m'000005.XSHE'\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m      3\u001b[0m \u001b[1;31m# 设置我们要操作的股票池\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 4\u001b[1;33m \u001b[0mset_universe\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mstocks\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[1;31mNameError\u001b[0m: name 'set_universe' is not defined"
     ]
    }
   ],
   "source": [
    "\n",
    " \n",
    "# 定义一个全局变量, 保存要操作的证券\n",
    "stocks = ['000001.XSHE','000002.XSHE','000004.XSHE','000005.XSHE']\n",
    "# 设置我们要操作的股票池\n",
    "set_universe(stocks)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "9a3481b4",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 初始化此策略\n",
    "def handle_data(context, data):\n",
    "    # 取得当前的现金\n",
    "    cash = context.portfolio.cash\n",
    "    # 循环股票列表\n",
    "    for stock in stocks:\n",
    "        # 获取股票的收盘价数据\n",
    "        prices = attribute_history(stock, 40, '1d', ('close'))\n",
    "        # 创建MACD买卖信号，包括三个参数fast period, slow period, and the signal\n",
    "        # 注意：MACD使用的price必须是narray\n",
    "        macd = MACD(prices['close'].values, fastperiod=12, slowperiod=26, signalperiod=9)\n",
    "        # 获取当前股票的数据\n",
    "        current_position = context.portfolio.positions[stock].amount\n",
    "        # 获取当前股票价格\n",
    "        current_price = data[stock].price\n",
    "        # 当MACD信号小于0，且拥有的股票数量大于0时，卖出所有股票\n",
    "        if macd < 0 and current_position > 0:\n",
    "            order_target(stock, 0)\n",
    "        # 当MACD信号大于0, 且拥有的股票数量为0时，则全仓买入\n",
    "        elif macd > 0 and current_position == 0:\n",
    "            number_of_shares = int(cash/current_price)\n",
    "            # 购买量大于0时，下单\n",
    "            if number_of_shares > 0:\n",
    "                # 买入股票\n",
    "                order(stock, +number_of_shares)\n",
    "                # 记录这次买入\n",
    "                log.info(\"Buying %s\" % (stock))\n",
    " \n",
    "# 定义MACD函数  \n",
    "def MACD(prices, fastperiod=12, slowperiod=26, signalperiod=9):\n",
    "#     '''\n",
    "#     参数设置:\n",
    "#         fastperiod = 12\n",
    "#         slowperiod = 26\n",
    "#         signalperiod = 9\n",
    "#     返回: macd - signal\n",
    "#     '''\n",
    "    macd, signal, hist = talib.MACD(prices, \n",
    "                                    fastperiod=fastperiod, \n",
    "                                    slowperiod=slowperiod, \n",
    "                                    signalperiod=signalperiod)\n",
    "    return macd[-1] - signal[-1]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fa2f25c6",
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "data[\"macd\"], data[\"macd_signal\"], data[\"macd_hist\"] = talib.MACD(data['Close'], fastperiod=12, slowperiod=26, signalperiod=9)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
